var x = 0;
var y = 0;
var trList = [];
var tableList = [];
/**
 * 获取焦点
 */
window.addEventListener('click', function () {
    /**
     * 获取整表模型
     */
    var table = document.activeElement.parentElement.parentElement.parentElement.parentElement;
    trList = table.getElementsByTagName('tr');
    tableList = initData(trList);
    /**
     * 获取当前坐标
     */
    x = getCurrentLocation(document.activeElement.parentElement);
    y = getCurrentLocation(document.activeElement.parentElement.parentElement);
});
/**
 * 判断是否为表格
 */
function isTable() {
    if (document.activeElement.tagName === 'INPUT') {
        if (document.activeElement.parentElement.tagName === 'TD') {
            if (document.activeElement.parentElement.parentElement.tagName === 'TR') {
                return true;
            }
        }
    }
    return false;
}
/**
 * 获取当前坐标
 */
function getCurrentLocation(item) {
    var before = 0;
    while (item.previousElementSibling !== null) {
        item = item.previousElementSibling;
        before++;
    }
    return before;
}
/**
 * 初始化表格
 */
function initData(trList) {
    var index = 0;
    var tableList = [];
    for (var _i = 0, trList_1 = trList; _i < trList_1.length; _i++) {
        var tr = trList_1[_i];
        var tdList = tr.getElementsByTagName('td');
        tableList.push([]);
        for (var _a = 0, tdList_1 = tdList; _a < tdList_1.length; _a++) {
            var td = tdList_1[_a];
            var inputList = td.getElementsByTagName('input');
            for (var _b = 0, inputList_1 = inputList; _b < inputList_1.length; _b++) {
                var input = inputList_1[_b];
                tableList[index].push(input);
            }
        }
        index++;
    }
    return tableList;
}
/**
 * 触发按键
 */
window.addEventListener('keydown', function (event) {
    if (isTable()) {
        switch (event.key) {
            /**
             * 上
             */
            case "ArrowUp":
                if (y > 0) {
                    y--;
                }
                break;
            /**
             * 右
             */
            case "ArrowRight":
                if (x < tableList[y].length - 1) {
                    x++;
                }
                break;
            /**
             * 下
             */
            case "ArrowDown":
                if (y < trList.length - 1) {
                    y++;
                }
                break;
            /**
             * 左
             */
            case "ArrowLeft":
                if (x > 0) {
                    x--;
                }
                break;
        }
        tableList[y][x].focus();
    }
});
